package com.lqian.demo02.part5.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 使用ThreadLocal类和线程池进行改造数据库连接工具类JdbcUtils
 * @author: Melody_LQ
 * @time: 2022/7/13 11:28 下午
 */
public class JdbcUtils2 {
	private static DataSource ds = null;

	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

	static {
		init();
	}

	private static void init() {
		Properties pro = new Properties();
		try {
			pro.load(JdbcUtils2.class.getClassLoader().getResourceAsStream("druid.properties"));
			ds =  DruidDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		//从当前线程中获取Connection
		Connection conn = threadLocal.get();
		if (conn == null){
			conn = ds.getConnection();
			//将conn绑定到当前线程
			threadLocal.set(conn);
		}
		return conn;
	}

	//返回一个DataSource对象，用于QueryRunner的构造
	public static DataSource getDataSource(){
		return ds;
	}

	//开启事务
	public static void startTransaction() {
		Connection conn = threadLocal.get();
		if (conn == null) {
			try {
				conn = getConnection();
				//把 conn绑定到当前线程上
				threadLocal.set(conn);
				//开启事务
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}

		}
	}

	/**
	 * 回滚事务
	 */
	public static void rollback(){
		Connection conn = threadLocal.get();
		if (conn!=null){
			try {
				conn.rollback();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 提交事务
	 */
	public static void commit(){
		Connection conn = threadLocal.get();
		if (conn!=null){
			try {
				conn.commit();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 关闭数据库连接(注意，并不是真的关闭，而是把连接还给数据库连接池)
	 */
	public static void close(){
		Connection conn = threadLocal.get();
		if (conn!=null){
			try {
				conn.close();
				//移除当前线程上绑定的conn
				threadLocal.remove();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}



}